const fs = require('fs');
const query = require('../utils/query')

let update1Sql = fs.createWriteStream(`./sql/update1.sql`);
let update2Sql = fs.createWriteStream(`./sql/update2.sql`);


// 非400 数据
(async () => {
    let items = await query("select bm.id, bm.gid, bm.bind_type, bm.extra, bmd.bus_model_pin, bmd.mcode from bussiness_model bm  left join  bussiness_model_dist bmd on bm.id = bus_model_id " +
        "where (bm.third_cloud_gid is NUll or bm.third_cloud_gid = '') and bm.bind_type != '400';")
    let string = "";
    items.forEach(item => {
        if(item.bus_model_pin && item.mcode == undefined ) {
            // 更新mcode
            string += `UPDATE bussiness_model_dist set mcode = '${item.gid}' where bus_model_id = ${item.id};` + "\n";
            // // 更新extra
            // try {
            //     // json字符串
            //     if(item.extra === '' || item.extra === null) {
            //         item.extra = {}
            //     }
            //     let extraObj = JSON.parse(item.extra)
            //     extraObj.typeId = item.gid;
            //     string += `UPDATE bussiness_model set extra = ${stringify(extraObj)} where id = ${item.id};` + "\n";
            // } catch (e) {
            //     // 非json字符串 不处理
            //     console.log(" 非json字符串 不处理", item.id, item.extra)
            // }
        }
    })
    update1Sql.write(string);
})();


// 400 数据
(async () => {
    // let items = await query("select id, gid, extra, bind_type from bussiness_model where (third_cloud_gid is NUll or third_cloud_gid = '') and bind_type = '400';")
    let items = await query("select bm.id, bm.gid, bm.bind_type, bm.extra, bmd.bus_model_pin, bmd.mcode from bussiness_model bm  left join  bussiness_model_dist bmd on bm.id = bus_model_id " +
        "where (bm.third_cloud_gid is NUll or bm.third_cloud_gid = '') and bm.bind_type = '400';")
    // 返回extra 有typeid的 model
    let modelFromExtra =  {}
    items.forEach(item => {
        let gid  = getGidByExtra(item)
        if(gid) {
            modelFromExtra[gid] = gid
        }
    })

    let modelGids = Object.keys(modelFromExtra).map(item =>  ("'" + item + "'")).join(",")
    let models = await query(`select bm.id, bm.gid, bm.extra, bmd.bus_model_pin from bussiness_model bm  left join  bussiness_model_dist bmd on bm.id = bmd.bus_model_id where bm.gid in (${modelGids});`)

    let string = "";
    items.forEach(item => {
        // extra 指向的真实model
        let orgModel = null
        let gid  = getGidByExtra(item)
        if(gid) {
            orgModel = models.filter(i => i.gid === gid)[0]
            if(orgModel) {
                if(item.bus_model_pin  && item.mcode == undefined) {
                    string += `UPDATE bussiness_model_dist set mcode = "${orgModel.gid}", bus_model_pin= "${orgModel.bus_model_pin}"  where bus_model_id = ${item.id};`  + "\n";
                } else {
                    // string += `INSERT INTO bussiness_model_dist (bus_model_id, bus_model_pin, remain, total, mcode) VALUES ("${item.id}", "${orgModel.bus_model_pin}", 100000, 100000,  "${orgModel.gid}");`  + "\n";
                }
            }
        } else {
            // 设置mcode  处理方式同非400
            string += `UPDATE bussiness_model_dist set mcode = "${item.gid}" where bus_model_id = ${item.id};`  + "\n";
        }
    })
    update2Sql.write(string);
})();

const getGidByExtra = (item) => {
    try {
        // json字符串
        let extraObj = JSON.parse(item.extra)
        if(extraObj.typeId !== null  && extraObj.typeId !== '') {
            return extraObj.typeId
        }
    } catch (e) {
        // 非json字符串 不处理
        console.log(" 非json字符串 不处理", item.id, item.extra)
    }
}


const stringify = (obj) => {
    return JSON.stringify(JSON.stringify(obj))
}
//
//
// SELECT bind_type, gid, extra  FROM `bussiness_model` where bind_type = "400";
//
// SELECT distinct extra FROM `bussiness_model`;
//
// select distinct extra, bind_type,  gid from bussiness_model where third_cloud_gid is NUll or third_cloud_gid = '';
//
// select distinct bind_type from bussiness_model where third_cloud_gid = "";
//
// select * from dim_bind_type where bind_type_id in (select distinct bind_type from bussiness_model where third_cloud_gid ='' or third_cloud_gid is null)
//
//
// select distinct factory_id from p_product1;
//
//
// select distinct publish, audited, status from bussiness_model
//
//
// select * from bussiness_model_dist where bus_model_id in (select id from bussiness_model where third_cloud_gid is NUll or third_cloud_gid = '')
//
//
// // 新增mcode字段
// alter table bussiness_model_dist add mcode varchar(32) not null comment '产品编码'；
// // 非400的model
// select distinct extra ,id, gid, bind_type from bussiness_model where third_cloud_gid is NUll or third_cloud_gid = '' and bind_type = "400";
// // 更新mcode
// UPDATE bussiness_model set mcode = 1 where bind_type = "400";
//
// select bm.id, bm.gid, bm.extra, bmd.bus_model_pin from  bussiness_model bm  left join  bussiness_model_dist bmd on bm.id = bus_model_id where bm.bind_type ="400" and (bm.third_cloud_gid ='' or bm.third_cloud_gid is null);
//
//
// select id, gid, bind_type from bussiness_model where id= 1773;
// select * from bussiness_model_dist where bus_model_id = 1585;








